package com.gtc.zsk.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.constant.CommonConstant;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.mapper.VipBankUserMapper;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserQueryRequest;
import com.gtc.zsk.model.entity.*;
import com.gtc.zsk.model.vo.QuestionBankQuestionVO;
import com.gtc.zsk.model.vo.UserVO;
import com.gtc.zsk.model.vo.VipBankUserVO;
import com.gtc.zsk.service.QuestionBankQuestionService;
import com.gtc.zsk.service.QuestionBankService;
import com.gtc.zsk.service.UserService;
import com.gtc.zsk.service.VipBankUserService;
import com.gtc.zsk.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 16153
* @description 针对表【vip_bank_user(vip题库用户)】的数据库操作Service实现
* @createDate 2025-01-24 20:03:22
*/
@Service
public class VipBankUserServiceImpl extends ServiceImpl<VipBankUserMapper, VipBankUser>
    implements VipBankUserService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionBankService questionBankService;

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;

    @Override
    @Transactional
    public void validAndAddVipBankUser(VipBankUser vipBankUser, boolean add) {
        ThrowUtils.throwIf(vipBankUser == null, ErrorCode.PARAMS_ERROR);
        // 题库和题目必须都存在
        Long userId = vipBankUser.getUserId();
        Long questionBankId = vipBankUser.getQuestionBankId();
        ThrowUtils.throwIf(userId == null || questionBankId == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在！");
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不存在！");
        // 更新用户会员等级
        Integer vipLevel = user.getVipLevel();
        if (vipLevel <= 5){
            User updateUser = new User();
            updateUser.setId(userId);
            updateUser.setVipLevel(vipLevel + 1);
            boolean result = userService.updateById(updateUser);
            ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "更新用户vip等级失败！");
        }
        // 写入数据库
        boolean result = this.save(vipBankUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "添加用户-题库关系绑定失败！");
    }

    @Override
    public VipBankUserVO getVipBankUserVO(VipBankUser vipBankUser, HttpServletRequest request) {
        // 对象转封装类
        VipBankUserVO vipBankUserVO = VipBankUserVO.objToVo(vipBankUser);
        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = vipBankUser.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        vipBankUserVO.setUser(userVO);
        // endregion
        return vipBankUserVO;
    }

    @Override
    public QueryWrapper<VipBankUser> getQueryWrapper(VipBankUserQueryRequest vipBankUserQueryRequest) {
        QueryWrapper<VipBankUser> queryWrapper = new QueryWrapper<>();
        if (vipBankUserQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = vipBankUserQueryRequest.getId();
        Long notId = vipBankUserQueryRequest.getNotId();
        String sortField = vipBankUserQueryRequest.getSortField();
        String sortOrder = vipBankUserQueryRequest.getSortOrder();
        Long questionBankId = vipBankUserQueryRequest.getQuestionBankId();
        Long userId = vipBankUserQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionBankId), "questionBankId", questionBankId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<VipBankUserVO> getVipBankUserVOPage(Page<VipBankUser> vipBankUserPage, HttpServletRequest request) {
        List<VipBankUser> vipBankUserList = vipBankUserPage.getRecords();
        Page<VipBankUserVO> vipBankUserVOPage = new Page<>(vipBankUserPage.getCurrent(), vipBankUserPage.getSize(), vipBankUserPage.getTotal());
        if (CollUtil.isEmpty(vipBankUserList)) {
            return vipBankUserVOPage;
        }
        // 对象列表 => 封装对象列表
        List<VipBankUserVO> vipBankUserVOList = vipBankUserList.stream().map(vipBankUser -> {
            return VipBankUserVO.objToVo(vipBankUser);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = vipBankUserList.stream().map(VipBankUser::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        vipBankUserVOList.forEach(vipBankUserVO -> {
            Long userId = vipBankUserVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            vipBankUserVO.setUser(userService.getUserVO(user));
        });
        // endregion
        vipBankUserVOPage.setRecords(vipBankUserVOList);
        return vipBankUserVOPage;
    }

    @Override
    public boolean checkUserVip(long questionId, long userId) {
        //  查看该题目属于哪些题库
        LambdaQueryWrapper<QuestionBankQuestion> questionBanksLambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                .select(QuestionBankQuestion::getQuestionBankId)
                .eq(QuestionBankQuestion::getQuestionId, questionId);
        List<QuestionBankQuestion> questionBankQuestions = questionBankQuestionService.list(questionBanksLambdaQueryWrapper);
        // 如果vip题目尚未加入任何题库  则直接不允许看
        if (CollUtil.isEmpty(questionBankQuestions))
            return false;
        Set<Long> ofQuestionBankIdSet = questionBankQuestions.stream().map(QuestionBankQuestion::getQuestionBankId).collect(Collectors.toSet());
        // 查看用户开通了哪些题库的vip
        LambdaQueryWrapper<VipBankUser> vipBankUserLambdaQueryWrapper = Wrappers.lambdaQuery(VipBankUser.class)
                .select(VipBankUser::getQuestionBankId)
                .eq(VipBankUser::getUserId, userId);
        List<VipBankUser> vipBankUsers = this.list(vipBankUserLambdaQueryWrapper);
        // 如果用户没开启任何vip 则肯定不允许看
        if (CollUtil.isEmpty(vipBankUsers))
            return false;
        Set<Long> hasQuestionBankIdSet = vipBankUsers.stream().map(VipBankUser::getQuestionBankId).collect(Collectors.toSet());
        // 取交集 没交集说明用户还没开启题库会员
        HashSet<Long> resultSet = new HashSet<>();
        resultSet.addAll(ofQuestionBankIdSet);
        resultSet.retainAll(hasQuestionBankIdSet);
        if (resultSet.size() == 0)
            return false;
        return true;

    }

    @Override
    @Transactional
    public boolean removeAndUpdateUserVipLevel(LambdaQueryWrapper<VipBankUser> lambdaQueryWrapper, Long userId) {
        boolean removeResult = this.remove(lambdaQueryWrapper);
        ThrowUtils.throwIf(!removeResult, ErrorCode.SYSTEM_ERROR, "移除用户-题库vip关系绑定失败！");
        User user = new User();
        user.setId(userId);
        LambdaQueryWrapper<VipBankUser> countLambdaQueryWrapper = Wrappers.lambdaQuery(VipBankUser.class)
                .select(VipBankUser::getId)
                .eq(VipBankUser::getUserId, userId);
        List<VipBankUser> vipBankUserList = this.list(countLambdaQueryWrapper);
        if (CollUtil.isNotEmpty(vipBankUserList) && vipBankUserList.size() < 6)
            user.setVipLevel(vipBankUserList.size());
        if (CollUtil.isEmpty(vipBankUserList))
            user.setVipLevel(0);
        if (CollUtil.isNotEmpty(vipBankUserList) && vipBankUserList.size() >= 6)
            return true;
        boolean updateUserResult = userService.updateById(user);
        ThrowUtils.throwIf(!updateUserResult, ErrorCode.SYSTEM_ERROR, "更新用户vip等级失败！");
        return true;
    }
}




